<?php
/**
 * Created by PhpStorm.
 * Author: leishaofa
 * Date: 2017/1/18 14:14
 */

class AuthRuleAccessModel extends Model
{
    protected $trueTableName = 'f_member_rel';

    /**
     * 获取用户所有顶级菜单
     * @param $user_id
     * @param int $type
     * @return array
     */
    public function getUserTopNav($user_id, $type = 0){
        $where = array(
            'a.m_id' => $user_id
        );
        $join = 'LEFT JOIN f_group b ON b.group_id=a.group_id';
        $rules = $this->alias('a')
            ->where($where)
            ->join($join)
            ->field('b.group_val')
            ->select();
        if(!$rules){
            return array();
        }
        $rules_str = '';
        foreach($rules as $v){
            $rules_str .= $v['group_val'] . ',';
        }
        $rules_str = rtrim($rules_str, ',');
        $rules_arr = array_unique(explode(',', $rules_str));
        $admin_menu_model = new AuthRuleModel();
        $menus = $admin_menu_model->getMenu($rules_arr, 1);
        return $menus;
    }

    /**
     * 获取用户某一个组下面的子菜单
     * @param $user_id //管理员id
     * @parame $type 查询类型 1：所有菜单 2：某个一级下面子菜单
     * @param $category_id 父亲菜单id
     * @return array|mixed|number
     */
    public function getUserLeftNav($user_id,$category_id)
    {
        $where = array(
            'a.m_id' => $user_id,
        );
        $join = 'LEFT JOIN f_group b ON b.group_id=a.group_id';
        $rules = $this->alias('a')
            ->where($where)
            ->join($join)
            ->field('b.group_val')
            ->select();
        if(!$rules){
            return array();
        }

        $rules_arr = array_unique(explode(',', $rules[0]['group_val']));
        $admin_menu_model = new AuthRuleModel();
        $menus = $admin_menu_model->getMenu($rules_arr,empty($category_id)?0:2);
        $a = [];
        foreach ($menus as $v){
            if(!empty($v['act_action'])){
                $v['act_action'] =substr(U(''.$v['act_group'].'/'.$v['act_action'].''),1);
            }
            $a[] = $v;
        }
        $menus = get_column($a,2);
        if(!empty($category_id)) {
            foreach ($menus as $key => $val) {
                if ($val['act_id'] == $category_id) {
                    $menus = $val[$val['act_id']];
                    break;
                } else {
                    unset($menus[$key]);
                    continue;
                }
            }
        }
        return $menus;
    }

    /**
     * 检查用户id所属的角色，为后台超级管理员 药企超级管理员 代表超级管理员 不能删除
     * @param $id
     * @return bool
     */
    public function checkUserId($id)
    {
        $role_id = $this->where(['user_id' => $id])->field('role_id')->find();
        if($role_id['role_id'] == 1 || $role_id['role_id'] == 2 || $role_id['role_id'] == 3){
           return false;
        }
    }

}